package com.nimble.smile.service;

import android.text.TextUtils;

import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import com.google.gson.Gson;
import com.nimble.smile.BuildConfig;
import com.nimble.smile.utils.SharedPreferenceHelper;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/8/12 0012.
 */
public class ServiceManager {

    private static final String END_POINT = "http://huma.mynimble.cn:8778/";
    //private static final String END_POINT = "http://192.168.31.186:8778/";

    private static ServiceManager ourInstance = new ServiceManager();

    private Service service;

    public static ServiceManager getInstance() {
        return ourInstance;
    }

    private ServiceManager() {
    }

    public void init() {
        service = buildService();
    }

    private Service buildService() {

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

        Interceptor mTokenInterceptor = chain -> {
            Request request = chain.request();
            String token = SharedPreferenceHelper.getSharedPreferenceString("token", "");
            if (!TextUtils.isEmpty(token)) {
                request = request.newBuilder()
                        .header("tk", token)
                        .build();
            }
            return chain.proceed(request);
        };


        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .cookieJar(new CustomCookieManager())
                .addInterceptor(mTokenInterceptor)
                .addInterceptor(loggingInterceptor);



        return new Retrofit.Builder()
                .baseUrl(END_POINT)
                .client(clientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
                .create(Service.class);
    }

    private static class CustomCookieManager implements CookieJar {

        private static final String KEY_COOKIES = "KEY_COOKIES";

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            List<String> cookieList = Stream.of(cookies)
                    .map(Cookie::toString)
                    .collect(Collectors.toList());


            SharedPreferenceHelper.setSharedPreferenceString(KEY_COOKIES, new Gson().toJson(cookieList));
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            String cookieList = SharedPreferenceHelper.getSharedPreferenceString(KEY_COOKIES, "[]");
            String[] userCookies = new Gson().fromJson(cookieList, String[].class);
            List<Cookie> cookies = new ArrayList<>();
            if (userCookies != null) {
                cookies = Stream.of(userCookies)
                        .map(cookie -> Cookie.parse(url, cookie))
                        .collect(Collectors.toList());
            }
            return cookies;
        }
    }

    public Service getService() {
        return service;
    }



}
